/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.unice.miage.oobdoo.servlet;

import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.google.gdata.client.http.AuthSubUtil;
import com.unice.miage.oobdoo.Config;
import com.unice.miage.oobdoo.entity.Utilisateur;
import com.unice.miage.oobdoo.helpfull.HelpFull;
import com.unice.miage.oobdoo.manager.UtilisateurManager;
import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Jeremy Romano
 */
@WebServlet(name = "AuthServlet", urlPatterns = {"/AuthServlet"})
public class AuthServlet extends HttpServlet {

    @EJB
    private UtilisateurManager utilisateurManager;
    String FACEBOOK_API_ID = "175962519155144";
    String FACEBOOK_API_SECRET = "320d63da1c62daae63cf457bb557f936";
    String FLICKR_API_KEY = "b530efd6e5a9f25353f2e85c7d452e02";
    String FLICKR_API_SECRET = "0fbc40addb1a6f53";
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession(true);

        int id = Integer.valueOf(session.getAttribute("id").toString());

        Utilisateur u = utilisateurManager.getUtilisateurById(id);

        String forwardTo = "utilisateur/lier.jsp";
        String source = request.getParameter("source");
        String origine = (String) request.getAttribute("origine");
        String del = request.getParameter("del");

        if (del != null && del.equalsIgnoreCase("1") && source != null) {
            if (source.equalsIgnoreCase("facebook")) {
                utilisateurManager.updateAccesTokenFB(u, null);
            } else if (source.equalsIgnoreCase("picasa")) {
                System.out.println(" picasa");
                utilisateurManager.updateAccesTokenPICASA(u, null);
            } else if (source.equalsIgnoreCase("flickr")) {
                System.out.println(" flickr");
                utilisateurManager.updateAccesTokenFLICKR(u, null);
            }
            source = null;
            origine = null;
        }

        boolean tokenFBExist = (u.getAccess_token_fb() != null);
        boolean tokenPExist = (u.getAccess_token_picasa() != null);
        boolean tokenFExist = (u.getAccess_token_flickr() != null);

        if (source != null && !(source.equalsIgnoreCase("facebook") || source.equalsIgnoreCase("picasa") || source.equalsIgnoreCase("flickr"))) {
            source = null;
        }

        if (tokenFBExist) {
            request.setAttribute("facebook", 1);
        }

        if (tokenPExist) {
            request.setAttribute("picasa", 1);
        }

        if (tokenFExist) {
            request.setAttribute("flickr", 1);
        }

        if (source != null) {
            System.out.println(">>>>>>>>>>>>>>>>>>>>> source == " + source);
            if (source.compareToIgnoreCase("facebook") == 0) {
                if (!tokenFBExist) {
                    String callbackUrl = URLEncoder.encode(Config.WEBURL + "/AuthServlet?source=facebook");
                    String scope = "user_photos,offline_access,photo_upload,publish_stream";

                    if (request.getParameter("code") == null) {
                        // Login Action
                        String facebookAuthorizeUrl = "https://graph.facebook.com/oauth/authorize?client_id=" + FACEBOOK_API_ID + "&redirect_uri=" + callbackUrl + "&scope=" + scope;
                        response.sendRedirect(facebookAuthorizeUrl);
                    } else {
                        String facebookTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + FACEBOOK_API_ID + "&client_secret=" + FACEBOOK_API_SECRET + "&code=" + request.getParameter("code") + "&redirect_uri=" + callbackUrl;

                        String access_token = HelpFull.getContentResult(new URL(facebookTokenUrl)).split("&")[0].split("=")[1];

                        utilisateurManager.updateAccesTokenFB(u, access_token);

                        forwardTo = "AuthServlet";
                        RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                        dp.forward(request, response);
                    }
                } else {
                    forwardTo = "utilisateur/lier.jsp";
                    RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                    dp.forward(request, response);
                }
            } else if (source.compareToIgnoreCase("picasa") == 0) {
                if (!tokenPExist) {
                    if (request.getParameter("token") == null) {
                        String callbackUrl = Config.WEBURL + "/AuthServlet?source=picasa";
                        String scope = "https://picasaweb.google.com/data/";
                        boolean secure = false;
                        boolean picasaSession = true;

                        String requestUrl = AuthSubUtil.getRequestUrl(callbackUrl, scope, secure, picasaSession);

                        response.sendRedirect(requestUrl);
                    } else {
                        try {
                            String token = request.getParameter("token");
                            String sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);

                            utilisateurManager.updateAccesTokenPICASA(u, sessionToken);

                            forwardTo = "AuthServlet";
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);
                        } catch (Exception ex) {
                            Logger.getLogger(ImportServlet.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                } else {
                    forwardTo = "utilisateur/lier.jsp";
                    RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                    dp.forward(request, response);
                }
            } else if (source.compareToIgnoreCase("flickr") == 0) {
                if (!tokenFExist) {
                    if (request.getParameter("frob") == null) {
                        // Si pas de frob, on fait la demande a flickr

                        String firstFrob = "";

                        try {
                            RequestContext requestContext;	// Used for making signed calls to Flickr
                            Flickr flickr = new Flickr(FLICKR_API_KEY, FLICKR_API_SECRET, new REST());

                            requestContext = RequestContext.getRequestContext();
                            requestContext.setSharedSecret(FLICKR_API_SECRET);

                            AuthInterface authInterface = flickr.getAuthInterface();
                            firstFrob = authInterface.getFrob();
                            URL url = authInterface.buildAuthenticationUrl(Permission.WRITE, firstFrob);
                            response.sendRedirect(url.toString());

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    } else {
                        // Sinon, on recupere le token !!
                        Auth auth;
                        RequestContext requestContext;	// Used for making signed calls to Flickr

                        try {
                            String fetchedFrob = request.getParameter("frob");
                            Flickr flickr = new Flickr(FLICKR_API_KEY, FLICKR_API_SECRET, new REST());

                            requestContext = RequestContext.getRequestContext();
                            requestContext.setSharedSecret(FLICKR_API_SECRET);

                            AuthInterface authInterface = flickr.getAuthInterface();
                            auth = authInterface.getToken(fetchedFrob);

                            requestContext.setAuth(auth);

                            utilisateurManager.updateAccesTokenFLICKR(u, auth.getToken());

                            forwardTo = "AuthServlet";
                            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                            dp.forward(request, response);

                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                } else {
                    forwardTo = "utilisateur/lier.jsp";
                    RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                    dp.forward(request, response);
                }
            } else {
                forwardTo = "AuthServlet";
                RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
                dp.forward(request, response);
            }
        } else {
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>> GOTO utilisateur/lier.jsp");
            forwardTo = "utilisateur/lier.jsp";
            RequestDispatcher dp = request.getRequestDispatcher(forwardTo);
            dp.forward(request, response);
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
